package com.xmindguoguo.boot.core;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.xmindguoguo.boot.util.json.JsonResult;

@Controller
public class BaseController {
    protected static String SUCCESS = "SUCCESS";
    protected static String ERROR = "ERROR";
    protected static String REDIRECT = "redirect:";
    protected static String FORWARD = "forward:";
    @Autowired
    public HttpServletRequest request;
    @Autowired
    public HttpServletResponse response;

    // ===================================
    /**
     * @Title forwordErrorMsg
     * @author 刘金浩
     * @date 2017年9月14日 下午3:27:08
     * @param
     * @return String
     */
    protected String getErrorMsg(List<ObjectError> list) {
        String message = "";
        for (ObjectError error : list) {
            DefaultMessageSourceResolvable d = (DefaultMessageSourceResolvable) error.getArguments()[0];
            message += d.getDefaultMessage() + ":" + error.getDefaultMessage() + "\n";
        }
        return message;
    }

    /**
     * 获取实体验证的错误信息
     * 
     * @Title getErrorMsg
     * @author 于国帅
     * @date 2018年11月24日 下午7:34:29
     * @param result
     * @return String
     */
    protected Object sendValidatedMsg(BindingResult result) {
        return JsonResult.sendError(getErrorMsg(result.getAllErrors()), null);
    }

    /**
     * 将request的参数设置到页面中 ,如果不传递参数默认全部都设置回去
     * 
     * @Title setAttr
     * @author 于国帅
     * @date 2018年12月8日 下午3:38:16
     * @param strs
     *            需要放回去的参数，不设置默 void
     */
    protected void setAttr(String... strs) {
        Enumeration<String> names = request.getParameterNames();
        if (ArrayUtils.isNotEmpty(strs)) {
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                if (ArrayUtils.contains(strs, name)) {
                    request.setAttribute(name, request.getParameter(name));
                }
            }
        }
    }

    protected void setAttr() {
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            request.setAttribute(name, request.getParameter(name));
        }
    }
}
